package cn.powerone.scm.service.impl;

import java.util.Date;
import java.util.List;
import cn.powerone.common.utils.DateUtils;
import cn.powerone.scm.domain.ScmProductsHistory;
import cn.powerone.scm.service.IScmProductsHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import cn.powerone.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import cn.powerone.scm.domain.ScmProductsSub;
import cn.powerone.scm.mapper.ScmProductsMapper;
import cn.powerone.scm.domain.ScmProducts;
import cn.powerone.scm.service.IScmProductsService;

/**
 * 产品Service业务层处理
 * 
 * @author PowerOne
 * @date 2025-06-27
 */
@Service
public class ScmProductsServiceImpl implements IScmProductsService 
{
    @Autowired
    private ScmProductsMapper scmProductsMapper;

    @Autowired
    private IScmProductsHistoryService scmProductsHistoryService;

    /**
     * 查询产品
     * 
     * @param id 产品主键
     * @return 产品
     */
    @Override
    public ScmProducts selectScmProductsById(Long id)
    {
        return scmProductsMapper.selectScmProductsById(id);
    }

    /**
     * 查询产品列表
     * 
     * @param scmProducts 产品
     * @return 产品
     */
    @Override
    public List<ScmProducts> selectScmProductsList(ScmProducts scmProducts)
    {
        return scmProductsMapper.selectScmProductsList(scmProducts);
    }

    @Override
    public ScmProducts selectScmProductsByDrawingNumber(String drawingNumber) {
        return scmProductsMapper.selectScmProductsByDrawingNumber(drawingNumber);
    }

    /**
     * 新增产品
     * 
     * @param scmProducts 产品
     * @return 结果
     */
    @Transactional
    @Override
    public int insertScmProducts(ScmProducts scmProducts)
    {
        //先确认内部版本号
        ScmProducts latestProducts = scmProductsMapper.selectScmProductsByDrawingNumber(scmProducts.getDrawingNumber());
        if (latestProducts != null){
            scmProducts.setInternalVersion(latestProducts.getInternalVersion() + 1);
        }
        // 新增
        long oldId = scmProducts.getParentId() == null ? 0 : scmProducts.getParentId();
        scmProducts.setParentId(0L);
        scmProducts.setCreateTime(DateUtils.getNowDate());
        int rows = scmProductsMapper.insertScmProducts(scmProducts);
        long newId = scmProducts.getId();
        insertScmProductsSub(scmProducts);
        if (oldId > 0 && rows > 0){
            List<ScmProducts> oldProductList = scmProductsMapper.selectScmProductsByParentId(oldId);
            for (ScmProducts product : oldProductList){
                product.setParentId(newId);
                scmProductsMapper.updateScmProducts(product);
            }
            ScmProducts oldProduct = scmProductsMapper.selectScmProductsById(oldId);
            if (oldProduct != null){
                oldProduct.setProductStatus(5L);
                oldProduct.setParentId(newId);
                scmProductsMapper.updateScmProducts(oldProduct);
            }
        }
        return rows;
    }

    /**
     * 修改产品
     * 
     * @param scmProducts 产品
     * @return 结果
     */
    @Transactional
    @Override
    public int updateScmProducts(ScmProducts scmProducts)
    {
        scmProducts.setUpdateTime(DateUtils.getNowDate());
        scmProductsMapper.deleteScmProductsSubByProductId(scmProducts.getId());
        insertScmProductsSub(scmProducts);
        //查询并比较product name 是否改变，如果改变 则写history
        ScmProducts oldProduct = scmProductsMapper.selectScmProductsById(scmProducts.getId());
        if (scmProducts.getProductName() != null && !oldProduct.getProductName().trim().equals(scmProducts.getProductName().trim())){
            ScmProductsHistory scmProductsHistory = new ScmProductsHistory();
            scmProductsHistory.setProductId(scmProducts.getId());
            scmProductsHistory.setFieldName("productName");
            scmProductsHistory.setOldValue(oldProduct.getProductName());
            scmProductsHistory.setNewValue(scmProducts.getProductName());
            scmProductsHistory.setCreateTime(DateUtils.getNowDate());
            scmProductsHistoryService.insertScmProductsHistory(scmProductsHistory);
        }

        return scmProductsMapper.updateScmProducts(scmProducts);
    }

    /**
     * 批量删除产品
     * 
     * @param ids 需要删除的产品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmProductsByIds(Long[] ids)
    {
        try{
            scmProductsMapper.deleteScmProductsSubByProductIds(ids);
            return scmProductsMapper.deleteScmProductsByIds(ids);
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            // 外键约束违反，无法删除有关联数据的记录
            System.err.println("删除失败：存在关联数据，无法删除");
            throw new RuntimeException("删除失败：存在关联数据，无法删除");
        } catch (Exception e) {
            System.err.println("删除过程中发生错误: " + e.getMessage());
            throw new RuntimeException("删除失败：" + e.getMessage());
        }
    }

    /**
     * 删除产品信息
     * 
     * @param id 产品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmProductsById(Long id)
    {
        int mainDeletedRows = 0;
        try{
            scmProductsMapper.deleteScmProductsSubByProductId(id);
            mainDeletedRows = scmProductsMapper.deleteScmProductsById(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return mainDeletedRows;
    }

    @Override
    public int selectProductsCountByMonth(Date yesterday) {
        return scmProductsMapper.selectProductsCountByMonth( yesterday);
    }

    @Override
    public int selectProductsCountByYear(Date yesterday) {
        return scmProductsMapper.selectProductsCountByYear( yesterday);
    }

    @Override
    public int selectProductsCountAll() {
        return scmProductsMapper.selectProductsCountAll();
    }

    /**
     * 新增产品子表信息
     * 
     * @param scmProducts 产品对象
     */
    public void insertScmProductsSub(ScmProducts scmProducts)
    {
        List<ScmProductsSub> scmProductsSubList = scmProducts.getScmProductsSubList();
        Long id = scmProducts.getId();
        if (StringUtils.isNotNull(scmProductsSubList))
        {
            List<ScmProductsSub> list = new ArrayList<ScmProductsSub>();
            for (ScmProductsSub scmProductsSub : scmProductsSubList)
            {
                scmProductsSub.setProductId(id);
                list.add(scmProductsSub);
            }
            if (list.size() > 0)
            {
                scmProductsMapper.batchScmProductsSub(list);
            }
        }
    }
}
